import os
from fastapi import UploadFile
from datetime import datetime
import aiofiles
import uuid

# 文件上传目录配置
UPLOAD_DIR = "uploads"
AVATAR_DIR = os.path.join(UPLOAD_DIR, "avatars")
APPEARANCE_DIR = os.path.join(UPLOAD_DIR, "appearances")
VOICE_DIR = os.path.join(UPLOAD_DIR, "voices")

# 确保上传目录存在
for dir in [AVATAR_DIR, APPEARANCE_DIR, VOICE_DIR]:
    os.makedirs(dir, exist_ok=True)

async def save_upload_file(upload_file: UploadFile, directory: str) -> str:
    """保存上传的文件，返回文件路径"""
    # 生成唯一文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    unique_id = str(uuid.uuid4().hex[:8])
    file_extension = os.path.splitext(upload_file.filename)[1]
    filename = f"{timestamp}_{unique_id}{file_extension}"
    
    # 完整的文件路径
    file_path = os.path.join(directory, filename)
    
    # 异步保存文件
    async with aiofiles.open(file_path, 'wb') as out_file:
        content = await upload_file.read()
        await out_file.write(content)
    
    return file_path 